/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.core.advice;

import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.io.Metric;
import cn.hallele.infrastructure.metadata.io.R;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.infrastructure.util.DateUtil;
import cn.hallele.infrastructure.util.NetUtil;
import cn.hallele.infrastructure.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 同一response封装处理
 *
 * @author anle5
 * @since 2024/9/15 11:11
 */
@Slf4j
@RestControllerAdvice
public class HalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 国际化
     */
    private final MessageSource i18n;

    /**
     * 国际化
     *
     * @param i18n 国际化
     */
    public HalResponseBodyAdvice(MessageSource i18n) {
        this.i18n = i18n;
    }

    /**
     * Whether this component supports the given controller method return type
     * and the selected {@code HttpMessageConverter} type.
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise
     */
    @Override
    public boolean supports(@NonNull MethodParameter returnType,
                            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * Invoked after an {@code HttpMessageConverter} is selected and just before
     * its write method is invoked.
     *
     * @param body                  the body to be written
     * @param returnType            the return type of the controller method
     * @param selectedContentType   the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request               the current request
     * @param response              the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull ServerHttpResponse response) {
        if (body instanceof Response<?> r) {
            return buildResponse(r);
        }

        if (ObjectUtil.isNull(body)) {
            log.warn("Api [{}] return a null response.Are you forget set response.System will build a empty successful Response", request.getURI());
            return buildResponse(R.ok(null));
        }

        log.warn("Unsupported response type: {}. System will not build std response.", response.getClass().getName());
        return body;
    }

    private Response<?> buildResponse(Response<?> body) {
        if (body.getMetric() != null) {
            // 说明处理过了
            return body;
        }

        return Response.builder()
                .metric(Metric.builder()
                        .success(true)
                        .msgCode(MsgCodeConst.SUCCESS)
                        .msgDesc(i18n.getMessage(MsgCodeConst.SUCCESS, new Object[]{}, LocaleContextHolder.getLocale()))
                        .requestId(NetUtil.getRequestId())
                        .completedTime(DateUtil.nowDate())
                        .build())
                .data(body.getData())
                .build();
    }
}
